<template>
  <div class="container-classification">
    <!-- 第一排：数据源分类 -->
    <div class="container1">

      <!-- 数据源分类 -->
      <div style="height: 15px; width: 5px; background-color: #394d5d"></div>
      <span style="margin-left: 10px; letter-spacing: 1px; color: #333333; font-size: 14px;">数据源分类</span>

      <!-- 添加分类 -->
      <img src="@/assets/images/添加分类.png" class="add">
      <span class="add2" @click="showAdd">添加分类</span>
    </div>

    <!-- 第二排：左搜索框 -->
    <div class="container2">
      <el-input v-model="filterText" style="width: 250px; height:30px; margin-top: 8px" size="large" placeholder="查询关键字"
        :suffix-icon="Search" />
    </div>

    <!-- 第三排：树形控件 -->
    <!-- 添加分类 弹出输入框 -->
    <span v-show="addFlag" class="input-new-fl">
      <img style="height: 14px;margin-left: 10px;" src="@/assets/images/树形控件1.png" />
      <el-input ref="inputDataCatRef" style="height: 22px; margin-left: 5px; width: 180px;" v-model="inputDataCat"
        @blur="addDataCat" />
    </span>

    <!-- 树形控件 -->
    <el-tree style="max-width: 250px; margin-left: 10px; border-radius: 5px;" :data="data" :props="defaultProps"
      highlight-current @node-click="handleNodeClick" ref="treeRef" :filter-node-method="filterNode" empty-text="暂无数据"
      :expand-on-click-node="false" default-expand-all>

      <!-- 树形插槽 -->
      <template #default="{ node, data }">
        <span class="treeSlot">

          <!-- 更多操作 编辑(重命名) 输入框 -->
          <span v-if=node.data.isRenameFlag>
            <img :src="data.icon" style="margin-right: 8px;margin-top: 2px; float: left;">
            <el-input style="height: 20px; width: 140px;" ref="inputRenameRef" v-model="inputRename"
              @blur="renameDataCat(node)" />
          </span>

          <!-- 正常状态 -->
          <span v-else>
            <img :src="data.icon" style="margin-right: 8px;margin-top: 5px; float: left;">
            <span style="padding-bottom: 5px; float: left;margin-top: 4px;">{{ node.label }}</span>
          </span>

          <!-- 更多操作 -->
          <span class="more" @click.stop @click="setPopVisible(node)">

            <!-- 更多操作 弹出卡片 -->
            <el-popover placement="bottom" trigger="click" hide-after="0" popper-style="padding:0px;"
              :visible=node.data.visible>

              <!-- 更多操作 图标 -->
              <template #reference>
                <div style="float: right; margin-right: 13px;">
                  <el-icon>
                    <More />
                  </el-icon>
                </div>
              </template>

              <!-- 更多操作 弹出框 三个按钮 -->
              <div @mouseleave="setPopDisvisible(node)">
                <el-button @click="moreCreate(node)" color="#1b364e" size="large" style="width:100px;margin-left: 24px;
                 margin-bottom:12px ;margin-top:12px">新建</el-button>
                <el-button @click="moreRename(node)" color="#1b364e" size="large" style="width:100px;margin-left: 24px;
                  margin-bottom:12px ; ">
                  编辑</el-button>
                <el-button color="#1b364e" size="large" style="width:100px;margin-left: 24px;margin-bottom:12px "
                  @click="moreDel(node)">删除</el-button>
              </div>
            </el-popover>
          </span>
        </span>
      </template>
    </el-tree>

    <!-- 更多操作 新建按钮 输入框 -->
    <span v-show="addFlag2" class="input-new-fl">
      <img style="height: 14px" src="@/assets/images/树形控件2.png" />
      <el-input ref="inputDataCatRef2" style="height: 22px; margin: 5px; width: 180;" v-model="inputDataCat2"
        @blur="addDataCat2" />
    </span>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { More } from "@element-plus/icons-vue";
import { Search } from '@element-plus/icons-vue'
import { ElTree } from 'element-plus'
import { onMounted } from 'vue';
import { ElMessageBox } from "element-plus";

// 当前树的第一个父节点、第一个子节点
// 可以用来默认展开树、展开当前操作结点（后弃用）
let firstCatPNode = '';
let firstCatCnode = '';

var currentNode;
// 设置更多操作弹出框 可见
function setPopVisible(node) {
  currentNode=node;
  node.data.visible = true;
}

// 设置更多操作弹出框 不可见
function setPopDisvisible(node) {
  node.data.visible = false;
}

// 设置更多操作 弹出框不可见            
// 监听整个文档的点击事件
document.addEventListener('click', function() {
    currentNode.data.visible = false;
});

// 更多操作 删除按钮 确认框
const moreDel = (node) => {
  ElMessageBox.confirm(
    '此操作将永久删除该目录, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // 用户点击了确定按钮
    console.log('删除目录');
    currenNodeId = node.data.id;
    await postDel(currenNodeId);
    fetchDataCat();
  }).catch(() => {
    // 用户点击了取消按钮或者关闭了对话框
    console.log('取消删除目录');
  });
}

// 更多操作 新建按钮
let currenNodeId = ''
let currenNodeIcon = ''
let currenNodePid = ''
async function moreCreate(node) {

  currenNodeId = node.data.id;
  currenNodePid = node.parent.data.id;
  currenNodeIcon = node.data.icon;
  node.data.visible = false;
  addFlag2.value = true;
  await console.log();
  inputDataCatRef2.value.focus();
}

// 更多操作 编辑（重命名）按钮
async function moreRename(node) {
  inputRename.value = node.data.label;
  currenNodeId = node.data.id;
  node.data.isRenameFlag = true;
  node.data.visible = false;
  await console.log();
  inputRenameRef.value.focus();
}

// Post 删除数据源
const postDel = async (dataCatId: string) => {
  try {
    const response = await axios.post('http://localhost:8080/datacat/del',
      {
        dataCatId
      });
    console.log("响应消息：", response.data.message);

  } catch (error) {
    console.error(error);
  }
};

// 设置添加分类 输入框 可见
function showAdd() {
  addFlag.value = true;
  inputDataCatRef.value.focus()
}

const addFlag = ref(false);
const addFlag2 = ref(false);
const inputDataCat = ref('')
const inputDataCat2 = ref('')
const inputRename = ref('')
const inputDataCatRef = ref()
const inputRenameRef = ref()
const inputDataCatRef2 = ref()

// 添加分类 创建父目录
const addDataCat = async () => {
  // 判空
  if (!inputDataCat.value) {
    addFlag.value = false;
    return;
  }

  // 判重
  if (isSame()) {
    alert("创建数据目录失败（已有同名目录）");
    inputDataCat.value = "";
    addFlag.value = false;
    return;
  }

  // 新建数据目录
  await createDataCat("0", inputDataCat.value)
  inputDataCat.value = "";
  addFlag.value = false;

  // 重新请求数据目录
  fetchDataCat();
}

// 更多操作 新建子目录
const addDataCat2 = async () => {
  // 判空
  if (!inputDataCat2.value) {
    addFlag2.value = false;
    console.log("输入为空！")
    return;
  }

  // 判重
  if (isSame2()) {
    alert("创建数据目录失败（已有同名目录）");
    inputDataCat2.value = "";
    addFlag2.value = false;
    return;
  }

  // 新建数据目录
  if (currenNodeIcon === "src/assets/images/树形控件1.png") {
    await createDataCat(currenNodeId, inputDataCat2.value)
  } else {
    await createDataCat(currenNodePid, inputDataCat2.value)
  }
  inputDataCat2.value = "";
  addFlag2.value = false;

  // 刷新数据目录
  fetchDataCat();
}

// 更多操作 编辑（重命名）目录
const renameDataCat = async (node) => {
  // 判空
  if (!inputRename.value) {
    node.data.isRenameFlag = false;
    console.log("重命名目录失败（输入为空）")
    return;
  }

  //没有更改
  if (inputRename.value === node.data.label) {
    console.log("重命名目录失败（未做更改）");
    inputRename.value = "";
    node.data.isRenameFlag = false;
    return;
  }

  // 判重
  if (isSame3()) {
    alert("重命名目录失败（已有同名目录）");
    inputRename.value = "";
    node.data.isRenameFlag = false;
    return;
  }

  // 重命名当前目录
  console.log("重命名目录：", currenNodeId, "为 ", inputRename.value)
  await postRename(currenNodeId, inputRename.value)
  inputRename.value = "";
  node.data.isRenameFlag = false;

  // 刷新目录
  fetchDataCat();
}

//  Post 重命名目录
const postRename = async (dataCatId: string, dataCatName: string) => {
  try {
    const response = await axios.post('http://localhost:8080/datacat/rename',
      {
        dataCatName,
        dataCatId
      });
    console.log("响应消息：", response.data.message);

  } catch (error) {
    console.error(error);
  }
};

// Get 创建目录
const createDataCat = async (pid: string, dataCatName: string) => {
  try {
    // console.log(dataCatPid);
    const response = await axios.get('http://localhost:8080/datacat/create', {
      params: {
        pid,
        dataCatName
      }
    });
    console.log(response.data.message);
  } catch (error) {
    console.error(error);
  }
};

// 树形目录名称查重
const isSame = () => {
  return findSameLabel(data.value, inputDataCat.value);
};

const isSame2 = () => {
  return findSameLabel(data.value, inputDataCat2.value);
};

const isSame3 = () => {
  return findSameLabel(data.value, inputRename.value);
};

// 全目录查重
const findSameLabel = (tree, value) => {
  for (const child of tree) {
    if (child.label == value) return true;
    if (child.children && Array.isArray(child.children)) {
      if (findSameLabel(child.children, value))
        return true;
    }
  }
  return false;
};

// 树形控件 数据
interface Tree {
  [key: string]: any
}

// 树形控件 上方搜索框
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

// 组件通信
let props = defineProps(['sendLabel'])
const handleNodeClick = (data: Tree) => {
  props.sendLabel(data.label)
}

// 组件挂载时，请求目录并打印
import axios from 'axios';
const data = ref<Tree[]>([]);
const fetchDataCat = async () => {
  try {
    const response = await axios.get('http://localhost:8080/datacat/querydatacat');
    console.log("刷新数据目录：", response.data.data);
    data.value = response.data.data;
    // console.log("1111", data.value[0].children[0].id);
    firstCatCnode = data.value[0].children[0].id;
    // console.log("第一个子结点：", firstCatCnode);
    firstCatPNode = data.value[0].id;
    // console.log(firstCatPNode)
  } catch (error) {
    throw error;
  }
};

onMounted(() => {
  fetchDataCat();
});

const defaultProps = {
  children: 'children',
  label: 'label',
  icon: 'icon'
}
</script>

<style scoped>
.container-classification {
  background-color: white;
  border-radius: 5px;
  margin-top: 10px;
  margin-left: 10px;
  width: 270px;
  height: calc(100vh - 120px);
}

.add {
  margin-left: 75px;
}

.container1 {
  width: 250px;
  margin-left: 10px;
  height: 35px;
  border-bottom: 1px solid #c3c7cb;
  display: flex;
  align-items: center;
}

.container2 {
  margin-left: 10px;
  width: 250px;
  height: 46px;
}

.input-new-fl {
  display: flex;
  align-items: center;
  padding: 0 24px;
}

.add2 {
  font-size: 14px;
  color: #666666;
  margin-left: 10px;
}

.add2:hover {
  color: #409eff;
}

.tree-node-popover {
  text-align: center;
  padding: 5px;
}

.threeOp {
  width: 70px;
  margin-left: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #1e3c55;
  padding: 10px;
  margin-bottom: 10px;
  color: white;
  border-radius: 8px;
}

.threeOp:hover {
  background-color: #2c5679;
}

.moreIcon {
  background-color: aqua;
  width: 40px;
  transition: opacity 0.1s ease;
  opacity: 0;
  float: right;
}

.treeSlot {
  align-items: center;
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.treeSlot:hover .more {
  opacity: 1;
}

.more {
  margin-right: 0px;
  width: 60px;
  transition: opacity 0.1s ease;
  opacity: 0;
}

.popper {
  padding: 0px !important;
}
</style>